package reflect;

import java.lang.reflect.Field;

/**
 * Created by baoyunfeng on 2018/1/11.
 */
public class ReflectField {

    public static void main(String args[]) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {


        Class clazz = Class.forName("reflect.UserModel");

        UserModel userModel = new UserModel();

        Field publicNameField = clazz.getField("publicName");
        publicNameField.set(userModel,"山东");
        System.out.println("publicNameField:"+publicNameField+"      "+publicNameField.get(userModel));


        //获取所有修饰符为public的字段,包含父类字段,注意修饰符为public才会获取
        Field fields[] = clazz.getFields();
        for (Field f:fields) {
            System.out.println("f:"+f.getDeclaringClass());
        }

        System.out.println("================getDeclaredFields====================");
        //获取当前类所字段(包含private字段),注意不包含父类的字段
        Field fields2[] = clazz.getDeclaredFields();
        for (Field f:fields2) {
            System.out.println("f2:"+f.getDeclaringClass()+"  "+f.getName());
        }
        //获取指定字段名称的Field类,可以是任意修饰符的自动,注意不包含父类的字段
        Field ageField = clazz.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(userModel,11);
        System.out.println("ageField:"+ageField+"    "+ageField.get(userModel));
    }
}
